﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using NB.MGJ.Common.API;
using NB.MGJ.Common;
using NB.MGJ.Model;
using NB.MGJ.Common.Cache;
using NB.MGJ.Common.Utility;
using System.Net.Http;

namespace NB.MGJ.API
{
    /// <summary>
    /// 获取IP
    /// </summary>
    public static class GetClientIp
    {
        private const string HttpContext = "MS_HttpContext";
        private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
        private const string OwinContext = "MS_OwinContext";

        public static string GetClientIpAddress(this HttpActionContext request)
        {
            try
            {
                if (request.Request.Properties.ContainsKey(HttpContext))
                {
                    dynamic ctx = request.Request.Properties[HttpContext];
                    if (ctx != null)
                    {
                        return ctx.Request.UserHostAddress;
                    }
                }

                if (request.Request.Properties.ContainsKey(RemoteEndpointMessage))
                {
                    dynamic remoteEndpoint = request.Request.Properties[RemoteEndpointMessage];
                    if (remoteEndpoint != null)
                    {
                        return remoteEndpoint.Address;
                    }
                }

                if (request.Request.Properties.ContainsKey(OwinContext))
                {
                    dynamic owinContext = request.Request.Properties[OwinContext];
                    if (owinContext != null)
                    {
                        return owinContext.Request.RemoteIpAddress;
                    }
                }
                return string.Empty;
            }
            catch (Exception)
            {

                return string.Empty;
            }
           
        }
    }

    /// <summary>
    /// 登录验证
    /// </summary>
    public class ApiAuthorizeFilter : AuthorizationFilterAttribute
    {

        //请求状态
        private bool requestisvalid = true;
        private bool RequestIsValid
        {
            get
            {
                return requestisvalid;
            }
            set
            {
                requestisvalid = value;
            }
        }

        /// <summary>
        ///失败返回内容
        /// </summary>
        private StringContent _ResponeContent { get; set; }
        
        public bool NeedLogOn { get; set; }

        public ApiAuthorizeFilter()
        {
            NeedLogOn = true;
        }



        public override void OnAuthorization(HttpActionContext actionContext)
        {
            string access_token = string.Empty, access_sign = string.Empty, access_timespan = string.Empty;
            Parallel.Invoke(() => {
                access_token = GetAccessTokenFormContext(actionContext);
            }, () => {
                access_sign = GetAccessSignFormContext(actionContext);
            }, () => {
                access_timespan = GetAccessTimeSpanFromContext(actionContext);
            });
            //access_token = GetAccessTokenFormContext(actionContext);
            //access_sign = GetAccessSignFormContext(actionContext);
            //access_timespan = GetAccessTimeSpanFromContext(actionContext);
            if (string.IsNullOrWhiteSpace(access_token) || string.IsNullOrWhiteSpace(access_sign))
            {
                RequestIsValid = false;
                _ResponeContent = new StringContent("请求失败");
            }
            if ((actionContext.ControllerContext.Controller is ApiBaseController<LogOnUserModel>) && RequestIsValid)
            {
                var _controller = actionContext.ControllerContext.Controller as ApiBaseController<LogOnUserModel>;

                _controller.UserIp = GetClientIp.GetClientIpAddress(actionContext);

                _controller.LogOnUser = UserHelperForApi.GetUserInfo(access_token);

                if (_controller.LogOnUser == null && NeedLogOn == true)
                {
                    RequestIsValid = false;
                    _ResponeContent = new StringContent("请重新登录");
                }
            }
            if (!RequestIsValid)
            {
                RequestIsValid = true;
                actionContext.Response = new HttpResponseMessage() { Content = _ResponeContent, StatusCode = System.Net.HttpStatusCode.NoContent };
            }
        }

        /// <summary>
        /// 从请求头中获取Token
        /// </summary>

        private string GetAccessTokenFormContext(HttpActionContext actionContext)
        {
            IEnumerable<string> _values = null;
            if (actionContext.Request.Headers.TryGetValues("Access-Token", out _values))
            {
                if (_values != null && _values.Count() != 0)
                {
                    return _values.FirstOrDefault();
                }
                return null;
            }
            else
            {
                HttpContextBase context = (HttpContextBase)actionContext.Request.Properties["MS_HttpContext"];
                HttpRequestBase request = context.Request;
                return request["Access-Token"];
            }
        }

        /// <summary>
        /// 从请求头中获取Sign
        /// </summary>
        private string GetAccessSignFormContext(HttpActionContext actionContext)
        {
            string _sign = string.Empty;
            IEnumerable<string> _values = null;
            if (actionContext.Request.Headers.TryGetValues("Access-Sign", out _values))
            {
                if (_values != null && _values.Count() != 0) {
                    return _values.FirstOrDefault();
                }
                return null;
            }
            else
            {
                HttpContextBase context = (HttpContextBase)actionContext.Request.Properties["MS_HttpContext"];
                HttpRequestBase request = context.Request;
                return request["Access-Sign"];
            }
          
        }
       
      


        /// <summary>
        /// 从请求头中获取时间戳
        /// </summary>
        private string GetAccessTimeSpanFromContext(HttpActionContext actionContext)
        {
            IEnumerable<string> _values = null;
            if (actionContext.Request.Headers.TryGetValues("Access-TimeSpan", out _values))
            {
                if (_values != null && _values.Count() != 0) return _values.FirstOrDefault();
                return null;
            }
            else
            {
                HttpContextBase context = (HttpContextBase)actionContext.Request.Properties["MS_HttpContext"];
                HttpRequestBase request = context.Request;
                return request["Access-TimeSpan"];
            }
        }
    }
}
